import notifyUserAllReadApi from '@/api/notify/notifyUserAllReadApi'
import notifyUserPageApi from '@/api/notify/notifyUserPageApi'
import notifyUserReadApi from '@/api/notify/notifyUserReadApi'
import { getAppNav } from '@/App'
import { checkIdSet } from '@/components/CAddOrderNo/CAddOrderNo'
import CSearchForm from '@/components/CSearchForm/CSearchForm'
import CTable from '@/components/CTable/CTable'
import { INotifyPageForm } from '@/model/form/notify/INotifyPageForm'
import INotifyVO from '@/model/vo/notify/INotifyVO'
import { execConfirm, ToastSuccess } from '@/util/CommonUtil'
import { dateFormat } from '@/util/DateUtil'
import { IconRefresh, IconSearch } from '@douyinfe/semi-icons'
import {
  Badge,
  Button,
  ButtonGroup,
  Dropdown,
  Form,
  Modal,
  Row,
  Space,
} from '@douyinfe/semi-ui'
import { FormApi } from '@douyinfe/semi-ui/lib/es/form'
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'
import NotifyColumns from './NotifyColumns'
import NotifyFormItem, { getNotifySearchFormSelectData } from './NotifyFormItem'
import NotifySearchFormItem from './NotifySearchFormItem'

export default function Notify() {
  const [selectedRowKeyList, setSelectedRowKeyList] = useState<
    (string | number)[]
  >([]) // 表格选中的 key集合
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState<INotifyVO[]>([])
  const [initForm, setInitForm] = useState<INotifyVO>({} as INotifyVO) // modal表单初始值
  const [modalTitle, setModalTitle] = useState('')
  const [modalVisible, setModalVisible] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false) // modal确认按钮的 loading状态
  const [sideSheetVisible, setSideSheetVisible] = useState(false) // 搜索 sideSheet是否显示
  const [searchForm, setSearchForm] = useState<INotifyPageForm>({}) // 搜索表单初始值

  const [total, setTotal] = useState(0)
  const [pageNum, setPageNum] = useState(1)
  const [pageSize, setPageSize] = useState(10)

  const formApi = useRef<FormApi>()

  // 执行获取 table数据
  function doGetTableData() {
    getTableData(
      setDataSource,
      setLoading,
      searchForm,
      pageNum,
      pageSize,
      setTotal
    )
  }

  const { dictList } = getNotifySearchFormSelectData(sideSheetVisible)

  useEffect(() => {
    doGetTableData()
  }, [])

  return (
    <div className="p-l-r-20">
      <CSearchForm
        sideSheetVisible={sideSheetVisible}
        setSideSheetVisible={setSideSheetVisible}
        getTableData={(values: any) => {
          setPageNum(1) // 这里的值不会立即生效
          setPageSize(10) // 这里的值不会立即生效
          getTableData(setDataSource, setLoading, values, 1, 10, setTotal)
        }}
        setSearchForm={setSearchForm}
        width={410}
      >
        <NotifySearchFormItem dictList={dictList}></NotifySearchFormItem>
      </CSearchForm>

      <Modal
        title={modalTitle}
        visible={modalVisible}
        okText="已读"
        onOk={() => {}}
        onCancel={() => {
          setModalVisible(false)
        }}
        maskClosable={false}
        confirmLoading={confirmLoading}
      >
        <Form
          onSubmit={(form) => {
            if (confirmLoading) return
          }}
          disabled={confirmLoading}
          getFormApi={(api) => (formApi.current = api)}
          initValues={initForm}
        >
          <Row gutter={30}>
            <NotifyFormItem dictList={dictList} />
          </Row>
        </Form>
      </Modal>

      <div className="flex jc-sb m-t-b-10">
        <Space>
          <Button
            theme="solid"
            onClick={() => {
              userAllReadClick(doGetTableData)
            }}
          >
            全部已读
          </Button>
          <Button
            theme="solid"
            type="warning"
            onClick={() => {
              if (!checkIdSet(selectedRowKeyList)) {
                return
              }
              userReadClick(selectedRowKeyList, doGetTableData)
            }}
          >
            已读
          </Button>
        </Space>

        {/* @ts-ignore */}
        <ButtonGroup>
          <Button
            onClick={() => {
              setSideSheetVisible(true)
            }}
            icon={
              <Badge dot={Object.keys(searchForm).length !== 0} type="warning">
                <IconSearch title="搜索" className="flex ai-c" />
              </Badge>
            }
          ></Button>
          <Button
            onClick={() => {
              if (!loading) {
                doGetTableData()
              }
            }}
            disabled={loading}
            icon={<IconRefresh spin={loading} title="刷新" />}
          ></Button>
        </ButtonGroup>
      </div>

      <CTable<INotifyVO>
        columns={NotifyColumns(dictList)}
        dataSource={dataSource}
        loading={loading}
        selectedRowKeyList={selectedRowKeyList}
        setSelectedRowKeyList={setSelectedRowKeyList}
        pagination={{
          total,
          currentPage: pageNum,
          pageSize,
          onChange: (currentPage: number, pageSize: number) => {
            setPageNum(currentPage) // 这里的值不会立即生效
            setPageSize(pageSize) // 这里的值不会立即生效
            getTableData(
              setDataSource,
              setLoading,
              searchForm,
              currentPage,
              pageSize,
              setTotal
            )
          },
          showSizeChanger: true,
        }}
        defaultOperateClickFun={(text, record, index) => {
          infoClick(record)
        }}
        operateDropdownItem={(text, record, index) => (
          <>
            <Dropdown.Item
              onClick={() => {
                infoClick(record)
              }}
            >
              查看详情
            </Dropdown.Item>
            {record.readFlag ? null : (
              <Dropdown.Item
                onClick={() => {
                  userReadClick([record.id], doGetTableData)
                }}
              >
                已读
              </Dropdown.Item>
            )}
          </>
        )}
      ></CTable>
    </div>
  )
}

// 获取 table数据
function getTableData(
  setDataSource: Dispatch<SetStateAction<INotifyVO[]>>,
  setLoading: Dispatch<SetStateAction<boolean>>,
  searchForm: INotifyPageForm,
  pageNum: number,
  pageSize: number,
  setTotal: Dispatch<SetStateAction<number>>
) {
  setLoading(true)
  notifyUserPageApi({
    ...searchForm,
    beginTime:
      searchForm.createTimeList && searchForm.createTimeList.length
        ? dateFormat(searchForm.createTimeList[0])
        : undefined,
    endTime:
      searchForm.createTimeList && searchForm.createTimeList.length
        ? dateFormat(searchForm.createTimeList[1])
        : undefined,
    pageNum,
    pageSize,
  })
    .then(({ data }) => {
      setDataSource(data.data.records)
      setTotal(data.data.total)
      setLoading(false)
    })
    .catch(() => {
      setLoading(false)
    })
}

// 当前用户：已读通知
function userReadClick(
  idList: (string | number)[],
  doGetTableData: () => void
) {
  execConfirm(
    () => {
      return notifyUserReadApi({ idSet: idList }).then(({ data }) => {
        ToastSuccess(data.msg)
        doGetTableData()
      })
    },
    undefined,
    '确定【已读】所选项吗？'
  )
}

// 当前用户：全部已读
function userAllReadClick(doGetTableData: () => void) {
  execConfirm(
    () => {
      return notifyUserAllReadApi().then(({ data }) => {
        ToastSuccess(data.msg)
        doGetTableData()
      })
    },
    undefined,
    '确定【全部已读】吗？'
  )
}

// 点击查看详情时
function infoClick(record: INotifyVO) {
  if (record.type === 1) {
    getAppNav()('/admin/sys-monitor/errorLog')
  }
}
